<template>
  <div v-loading="isloading" class="beian-container">
    <el-dialog :title="
        dialogStatus == 'add' ? '底图底数领取记录新增' : '底图底数领取记录编辑'
      " :visible.sync="isDialogShow" width="550px" :append-to-body="true" class="dialog1">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="left">
        <!-- <el-form-item
          label="行政区划选择:"
          prop="villageIds"
          v-if="dialogStatus == 'add'"
        >
          <el-cascader
            style="width: 300px"
            v-model="citySelected"
            :options="countyList"
            :props="props"
            size="medium"
            placeholder="请选择行政区划"
            clearable
            collapse-tags
            :show-all-levels="false"
            @change="handleChange"
            v-if="citySelectedShow"
          ></el-cascader>
        </el-form-item> -->
        <el-form-item label="行政区划选择:" prop="villageIds">
          <el-select v-model="form.villageIds" multiple placeholder="请选择" filterable  size="mini" style="width: 300px" >
            <el-option v-for="item in options" :key="item.id" :label="item.village+'-'+item.town" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领取编制单位:" prop="receiveOrganization">
             <el-select v-model="form.receiveOrganization"  placeholder="请先关联领取编制单位再选择" filterable  size="mini" style="width: 300px" @change="receivechange">
               <el-option v-for="item in receiveOrganizationList" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领取人:" prop="receiveName">
          <el-input type="text" :rows="2" placeholder="请输入领取人名" size="mini" clearable v-model="form.receiveName" style="width: 300px">
          </el-input>
        </el-form-item>
        <el-form-item label="联系方式:" prop="receivePhone">
          <el-input type="text" :rows="2" placeholder="请输入正确的电话号码" size="mini" clearable v-model="form.receivePhone" style="width: 300px">
          </el-input>
        </el-form-item>
        <el-form-item label="领取时间:" prop="receiveDate">
          <el-date-picker v-model="form.receiveDate" type="date" style="width: 300px" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus === 'add' ? submitForm('form') : updateData()">提交</el-button>
      </span>
    </el-dialog>
    <div>
      <div class="header">
        <i class="el-icon-d-arrow-right"></i>底图底数领取新增
      </div>
      <div class="header-button">
        <el-tooltip class="item" effect="dark" :content="'未领取底图数' + options.length" placement="bottom-start">
          <el-button type="danger" @click="open"><i class="el-icon-plus"></i>添加
          </el-button>
        </el-tooltip>
        <el-button type="primary" @click="download"><i class="el-icon-download"></i>导出</el-button>
      </div>
    </div>
    <div class="header">
      <i class="el-icon-d-arrow-right"></i>底图底数领取备案
    </div>
    <el-table :data="tableData" stripe border style="width: 100%" class="eltable">
      <el-table-column label="序号" width="150" type="index" />
          <el-table-column prop="villages" label="被领取村庄">
        <template slot-scope="scope">
          <div v-if="scope.row.villages.length > 0">
            <span>{{ scope.row.villages[0] }}</span><span class="vitotal" v-if="scope.row.villages.length > 1">等共{{ scope.row.villages.length }}个村庄</span>

            <a class="more" href="#" @click="openMore(scope.row.villages)">查看更多<i class="el-icon-d-arrow-right" /></a>
          </div>
          <div v-if="scope.row.villages.length == 0">无</div>
        </template>
      </el-table-column>

      <el-table-column prop="receiveOrganization" label="领取编制单位" width="150" />
      <el-table-column prop="receiveName" label="领取人" width="100" />
      <el-table-column prop="receivePhone" label="联系方式" width="100" />
      <el-table-column prop="receiveDate" label="领取时间 " width="100" />
      <el-table-column prop="recordUserName" label="发放人" width="100" />
      <el-table-column label="操作" width="255" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleUpdate(scope.row)" size="mini" plain><i class="el-icon-edit"></i>编辑
          </el-button>
          <el-button type="danger" @click="handleDelete(scope.row.id)" size="mini" plain><i class="el-icon-delete"></i>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-if="tableData.length > 0" class="elpagi" :total="total" @size-change="getdata" @current-change="getdata" @prev-click="getdata" @next-click="getdata" :current-page.sync="listquery.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size.sync="listquery.pageSize" layout="total,sizes, prev, pager, next, jumper" />
    <el-dialog title="村庄列表" :visible.sync="dialogVisible" width="30%" append-to-body>
      <ul class="villageul">
        <div class="allvilagestitle">领取村庄列表如下所示:</div>
        <li v-for="item in allvilages" :key="item">{{ item }}</li>
      </ul>
    </el-dialog>
  </div>
</template>
<script>
// import {
//   getlist,
//   getcitylist,
//   getcountrylist,
//   getvillagelistskip,
//   add,
//   edit,
//   del,
// } from "@/api/record.js";

import { handleCofirm } from "@/utils/confirm";
import {
  mapGetters
} from 'vuex'
import {
  getTownList,
  getAllVillageList,
  getlist,
   getlistdown,
  getlistall,
  add,
  edit,
  del,
} from "@/api/country.js";
import { gethasvillageids,gethasvillagenamelist } from "@/api/record.js";

export default {
    computed: {
    ...mapGetters([
      'citylist',
    ])
  },
  data () {
    return {
      villageIds: [],
      total: 0,
      dialogStatus: "",
      options: [],
      options1: [],
      receiveOrganizationList:[],
      citySelected: "",
      citySelectedShow: true,
      props: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        multiple: true,
      },
      form: {
        receiveOrganization: "",
        target: "",
        villageIds: [],
        receivePhone: "",
        receiveName: "",
        receiveDate: "",
      },
      rules: {
        villageIds: [
          { required: true, message: "请选择领取区域", trigger: "blur" },
        ],
        receivePhone: [
          { required: true, message: "请输入联系人电话号码", trigger: "blur" },
        ],
        receiveOrganization: [
          { required: true, message: "请输入领取编制单位", trigger: "blur" },
        ],
        receiveName: [
          { required: true, message: "请输入领取人名称", trigger: "blur" },
        ],
        receiveDate: [
          { required: true, message: "请选择领取时间", trigger: "blur" },
        ],
      },
      tableData: [],
      isloading: false,
      role: "",
      nowuserarea: "",
      isDialogShow: false,
      dialogVisible: false,
      allvilages: [],
      listquery: {
        pageSize: 10,
        currentPage: 1,
        userType: 2,
      },
    };
  },
  mounted () {
    this.getdata();
    gethasvillageids().then(res=> {
      this.options = res.data;
    }).catch(e=>{
      this.$message.error(e.response.data.message);
    })
    gethasvillagenamelist().then(res=> {
         
      this.receiveOrganizationList = res.data;
    }).catch(e=>{
      this.$message.error(e.response.data.message);
    })

        // profilelist().then(v=>{
          
        // })
   
    this.role = this.$store.getters.user.roles[0].name;
    // if (this.role == "湖南省第三测绘院" || this.role == "超级管理员") {
    //   this.getcitylistv();
    // } else {
    //   this.nowuserarea = this.$store.getters.user.area;
    //   this.form.area = this.nowuserarea;
    //   let list = this.nowuserarea.split("-");

    //   if (this.role == "市州用户") {
    //     this.getcountrylistv(list[0]);
    //   } else {
    //     this.getvillagelistskipv(list[0], list[1]);
    //   }
    // }
  },
  methods: {
    receivechange(){
      this.receiveOrganizationList.forEach(element => {
        if(element.name==this.form.receiveOrganization){
          this.form.receivePhone = element.contactPhone
          this.form.receiveName = element.userNames
        }
      });
    },
    handleChange (e) { },
       download() {
      this.isloading = true;
      let query = {
        pageSize: 9999,
        currentPage: 1,
      };
      getlistdown(query).then((res) => {
        let tablelist = res.data.content;
        this.downloadExcel(tablelist);
        this.isloading = false;
      });
    },
    downloadExcel(tabledatalist) {
      // let header = Object.keys(tabledatalist[0]);
      // let list2 = [];
      // for (var i = 0; i < tabledatalist.length; i++) {
      //   let list1 = [];
      //   for (var j = 0; j < header.length; j++) {
      //     let obj = tabledatalist[i];
      //     list1.push(obj[header[j]]);
      //   }
      //   list2.push(list1);
      // }
      const tHeader = [
            '市',
            '区县',
            '乡镇',
            '村庄',
            '领取人',
            '领取机构',
            '领取人电话',
            '领取时间',
          ]
          const filterVal = [
             'city',
            'country',
            'town',
            'village',
            'receiveName',
            'receiveOrganization',
            'receivePhone',
            'receiveDate',
          ]
          const data = this.formatJson(filterVal, tabledatalist)
      export_json_to_excel({
        header: tHeader,
        data,
        filename: "编制单位底图底数领取备案记录",
      });
    },
    formatJson(filterVal, listdata) {
      return listdata.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    async getdata () {
      this.isloading = true;
      let res = await getlist(this.listquery);
      this.tableData = res.data.content;
      this.total = res.data.totalElements;
      this.isloading = false;
    },
    openMore (villages) {
      this.dialogVisible = true;
      this.allvilages = villages;
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const temp = Object.assign({}, this.form);
 
          temp.villageIds = temp.villageIds.toString();
          temp.userType = 2
          add(temp)
            .then((v) => {
              this.getdata();
              this.$notify({
                title: "成功",
                message: "添加成功",
                type: "success",
              });
              this.isDialogShow = false;
            })
            .catch((error) => {
              this.$notify.error({
                title: "错误",
                message: error,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    handleUpdate (row) {
      row.villageIds = row.villageIds.split(",")
      this.form = Object.assign({}, row); // copy obj
      this.dialogStatus = "edit";
      this.isDialogShow = true;
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    updateData () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const temp = Object.assign({}, this.form);
     
          temp.villageIds = temp.villageIds.toString();
          edit(temp).then(() => {
            this.getdata();
            this.isDialogShow = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete (id) {
      handleCofirm("确认要删除吗？", "warning").then((res) => {
        del(id)
          .then((v) => {
            this.getdata();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
            });
            this.isDialogShow = false;
          })
          .catch((error) => {
            this.$notify.error({
              title: "错误",
              message: error,
            });
          });
      });
    },
    open () {
      this.form = {
        area: this.nowuserarea,
        target: "",
        villageIds: [],
        receiveName: "",
        receivePhone:"",
        receiveDate: "",
      };
      this.dialogStatus = "add";
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
      this.isDialogShow = true;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../public/css/table.scss";
.villageul {
  margin: 0;
  padding: 5px;
  list-style: none;
  border: 1px dashed #ccc;
  max-height: 250px;
  overflow-y: auto;
  li {
    line-height: 25px;
  }
}
.allvilagestitle {
  line-height: 35px;
  color: #4778c7;
}
.more {
  color: #4cc8c7;
  margin-left: 10px;
  &:hover {
    color: orange;
  }
}
.beian-container {
  margin: 5px;
  height: 100%;
  overflow: auto;
  background-color: #fff;
}
::v-deep .el-header {
  display: flex;
  align-items: center;
  padding: 0px 5px;
}

.item {
  margin-right: 15px;
}

.header-button {
  padding: 10px;
  display: flex;
  justify-content: space-between;
}

.header {
  font-size: 14px;
  font-weight: 600;
  line-height: 35px;
  margin-right: 5px;
  border-bottom: 1px dashed #ccc;

  i {
    color: #4778c7;
  }
}
</style>